<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

function pick_language()
{
	require APPPATH.'/config/language.php';

    // Re-populate $_GET
	parse_str($_SERVER['QUERY_STRING'], $_GET);
	
	// If we've been redirected from HTTP to HTTPS on admin, ?session= will be set to maintain language
	if ($_SERVER['SERVER_PORT'] == 443 and ! empty($_GET['session']))
	{
		session_start($_GET['session']);
	}
	
	else
	{
		session_start();
	}
		
    // Lang set in URL via ?lang=something
    if ( ! empty($_GET['lang']))
    {
        // Turn en-gb into en
        $lang = strtolower(substr($_GET['lang'], 0, 2));

    	log_message('debug', 'Set language in URL via GET: '.$lang);
    }

    // Lang has already been set and is stored in a session
    elseif ( ! empty($_SESSION['lang_code']) )
    {
        $lang = $_SESSION['lang_code'];

    	log_message('debug', 'Set language in Session: '.$lang);
    }

    // Lang has is picked by a user.
    elseif ( ! empty($_COOKIE['lang_code']) )
    {
        $lang = strtolower($_COOKIE['lang_code']);

    	log_message('debug', 'Set language in Cookie: '.$lang);
    }

    // Still no Lang. Lets try some browser detection then
    elseif ( ! empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
    {
    	// explode languages into array
    	$accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);

		$supported_langs = array_keys($config['supported_languages']);

    	log_message('debug', 'Checking browser languages: '.implode(', ', $accept_langs));

    	// Check them all, until we find a match
    	foreach ($accept_langs as $accept_lang)
    	{
			if (strpos($accept_lang, '-') === 2)
			{
				// Turn pt-br into br
				$lang = strtolower(substr($accept_lang, 3, 2));

				// Check its in the array. If so, break the loop, we have one!
				if (in_array($lang, $supported_langs))
				{
					log_message('debug', 'Accept browser language: '.$accept_lang);

					break;
				}
			}

    		// Turn en-gb into en
    		$lang = strtolower(substr($accept_lang, 0, 2));

    		// Check its in the array. If so, break the loop, we have one!
    		if (in_array($lang, $supported_langs))
    		{
		    	log_message('debug', 'Accept browser language: '.$accept_lang);

    			break;
    		}
    	}
    }

    // If no language has been worked out - or it is not supported - use the default
    if (empty($lang) OR ! array_key_exists($lang, $config['supported_languages']))
    {
        $lang = $config['default_language'];

    	log_message('debug', 'Set language default: '.$lang);
    }

    // Whatever we decided the lang was, save it for next time to avoid working it out again
    $_SESSION['lang_code'] = $lang;

    // Load CI config class
    $CI_config =& load_class('Config');

    // Set the language config. Selects the folder name from its key of 'en'
    $CI_config->set_item('language', $config['supported_languages'][$lang]['folder']);

    // Sets a constant to use throughout ALL of CI.
    define('AUTO_LANGUAGE', $lang);
	
    log_message('debug', 'Defined const AUTO_LANGUAGE: '.AUTO_LANGUAGE);
	
    $segment_array = explode( '/', strtolower( detect_uri()) );
	if(in_array( $segment_array[0],available_language_code())){
		$_SESSION['sys_lang_code'] = $segment_array[0];	
		setcookie("sys_lang", $segment_array[0], time()+604800);
	}else{
	   if(isset($_SESSION['sys_lang_code'])){
	       $_SESSION['sys_lang_code'] = $_SESSION['sys_lang_code'];	
		   setcookie("sys_lang", $_SESSION['sys_lang_code'], time()+604800);
	   }elseif(isset($_COOKIE["sys_lang"])){
	       $_SESSION['sys_lang_code'] = $_COOKIE["sys_lang"];	
	   }else{
	       $_SESSION['sys_lang_code'] = "es";	
		   setcookie("sys_lang", "es", time()+604800);
	   }    
	   
	}
	/*
	if(isset($_SESSION['sys_lang_code']) AND in_array( $segment_array[0],available_language_code()) AND $segment_array[0] != $_SESSION['sys_lang_code']){
		$_SESSION['sys_lang_code'] = $segment_array[0];	
		setcookie("sys_lang", $segment_array[0], time()+604800);
	}
	
	if(isset( $_COOKIE["sys_lang"] ) AND !isset($_SESSION['sys_lang_code']) ){
		$_SESSION['sys_lang_code'] = $_COOKIE["sys_lang"];
	}
	if( !isset( $_COOKIE["sys_lang"] ) AND !isset($_SESSION['sys_lang_code'])) {
		$_SESSION['sys_lang_code'] = getDefaultLanguage();
		setcookie("sys_lang", getDefaultLanguage(), time()+604800);
	}
    */
}

 function detect_uri()
	{
		if ( ! isset($_SERVER['REQUEST_URI']) OR ! isset($_SERVER['SCRIPT_NAME']))
		{
			return '';
		}

		$uri = $_SERVER['REQUEST_URI'];
		if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0)
		{
			$uri = substr($uri, strlen($_SERVER['SCRIPT_NAME']));
		}
		elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0)
		{
			$uri = substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME'])));
		}

		// This section ensures that even on servers that require the URI to be in the query string (Nginx) a correct
		// URI is found, and also fixes the QUERY_STRING server var and $_GET array.
		if (strncmp($uri, '?/', 2) === 0)
		{
			$uri = substr($uri, 2);
		}
		$parts = preg_split('#\?#i', $uri, 2);
		$uri = $parts[0];
		if (isset($parts[1]))
		{
			$_SERVER['QUERY_STRING'] = $parts[1];
			parse_str($_SERVER['QUERY_STRING'], $_GET);
		}
		else
		{
			$_SERVER['QUERY_STRING'] = '';
			$_GET = array();
		}

		if ($uri == '/' || empty($uri))
		{
			return '/';
		}

		$uri = parse_url($uri, PHP_URL_PATH);

		// Do some final cleaning of the URI and return it
		return str_replace(array('//', '../'), '/', trim($uri, '/'));
	}
 

